import { useId } from '@vueuse/core'
import { ref, computed } from 'vue'
import { 
  generateSnowflakeId, 
  parseSnowflakeId, 
  validateSnowflakeId,
  getMachineId,
  getEpoch
} from '@/utils/snowflakeId.js'

/**
 * 雪花ID组合式函数
 * 基于VueUse的useId和自定义雪花ID生成器
 */
export function useSnowflakeId() {
  // 使用VueUse的useId作为基础ID
  const baseId = useId()
  
  // 当前雪花ID
  const currentId = ref('')
  
  // 生成新的雪花ID
  const generateId = () => {
    currentId.value = generateSnowflakeId()
    return currentId.value
  }
  
  // 解析雪花ID
  const parseId = (id) => {
    try {
      return parseSnowflakeId(id)
    } catch (error) {
      console.error('解析雪花ID失败:', error)
      return null
    }
  }
  
  // 生成带前缀的雪花ID
  const generatePrefixedId = (prefix = '') => {
    const id = generateSnowflakeId()
    return prefix ? `${prefix}_${id}` : id
  }
  
  // 批量生成雪花ID
  const generateBatchIds = (count = 1) => {
    const ids = []
    for (let i = 0; i < count; i++) {
      ids.push(generateSnowflakeId())
    }
    return ids
  }
  
  // 计算属性：当前ID是否有效
  const isValidId = computed(() => {
    return currentId.value && validateSnowflakeId(currentId.value)
  })
  
  // 计算属性：当前ID的解析信息
  const currentIdInfo = computed(() => {
    if (!isValidId.value) return null
    return parseId(currentId.value)
  })
  
  // 计算属性：当前机器ID
  const machineId = computed(() => getMachineId())
  
  // 计算属性：起始时间戳
  const epoch = computed(() => getEpoch())
  
  return {
    // 响应式数据
    currentId,
    baseId,
    
    // 计算属性
    isValidId,
    currentIdInfo,
    machineId,
    epoch,
    
    // 方法
    generateId,
    parseId,
    generatePrefixedId,
    generateBatchIds,
    validateId: validateSnowflakeId
  }
} 